import { FC, useEffect, useMemo, useRef, useState } from "react";
import { pagingQueryByChatId } from "../../indexdb";
import { useAppState, useDB } from "../provider/context";
import { Msg } from "../msg";
import bg from "./bg.jpg";
import bg1 from "./bg1.jpg";
import bg2 from "./bg2.jpg";

const bgs = [bg, bg1, bg2];
const randomBg = () => {
  return bgs[Math.floor(Math.random() * bgs.length)];
};

//#region component Types
export interface ChatProps {
  chatId: string;
}
//#endregion component Types

const PageMsgSize = 30;

//#region component
export const Chat: FC<ChatProps> = (props) => {
  const { chatId } = props;
  const db = useDB();
  const { msgList, setMsgList } = useAppState();
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    console.log("当前消息数量", msgList.length);
  }, [msgList]);
  const bg = useMemo(() => randomBg(), []);
  const isEndRef = useRef(false);
  const loadedCount = useRef(0);
  const reset = () => {
    setMsgList([]);
    isEndRef.current = false;
    loadedCount.current = 0;
  };
  const query = () => {
    if (!loading && !isEndRef.current) {
      setLoading(true);
      pagingQueryByChatId(db, chatId, {
        limit: PageMsgSize,
        skipCount: loadedCount.current,
        filter(msg) {
          return msg.type !== 82;
        },
      })
        .then((result) => {
          const { count, data, isEnd, scanCount } = result;
          if (scanCount !== loadedCount.current) {
            setMsgList((prev) => [...prev, ...data]);

            loadedCount.current = scanCount;
            isEndRef.current = count < PageMsgSize ? true : isEnd;
          } else {
            console.log("scanCount === loadedCount.current");
            isEndRef.current = true;
          }
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  };

  useEffect(() => {
    reset();
    query(); // 初次加载时调用
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [chatId, db]);
  return (
    <div
      style={{
        padding: "10px",
        width: "60%",
        height: "100%",
        overflow: "auto",
        border: "1px solid #000",
        backgroundImage: `url(${bg})`,
        backgroundSize: "cover",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center",
        //反转
        display: "flex",
        flexDirection: "column-reverse",
      }}
      onScroll={(e) => {
        const target = e.target as HTMLDivElement;
        const scrollTop = Math.abs(target.scrollTop);
        const isTop =
          Math.abs(scrollTop + target.clientHeight - target.scrollHeight) < 10;

        if (isTop) {
          query();
        }
      }}
    >
      {msgList.map((msg) => {
        return <Msg key={msg.mid} data={msg} />;
      })}
    </div>
  );
};
//#endregion component
